package com.herysoft.scm.biz.sys;

import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.herysoft.scm.dao.sys.UserDao;
import com.herysoft.scm.model.sys.User;

public class UserBizImpl implements UserBiz,UserDetailsService{
	private UserDao userDao;
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	public UserDetails loadUserByUsername(String loginName)  throws UsernameNotFoundException, DataAccessException   {
		User user = userDao.getUserByLoginName(loginName);
		List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		if (user != null) 
		{
			if (!user.getEnabled() || user.getGroup() == null){
				return new org.springframework.security.core.userdetails.User(user.getLoginName(), user.getPwd(), user.getEnabled(), true, true,true, auths);
			}else{
				String roles[] = user.getGroup().getRoles().split(";");
				for (String role : roles) {
					GrantedAuthority auth = new GrantedAuthorityImpl(role);
					auths.add(auth);
				}
				return new org.springframework.security.core.userdetails.User(user.getLoginName(), user.getPwd(), true, true, true,true, auths);
			}
		}else{
			return null;
		}

	}
	public User getUserByLoginName(String loginName) {
		return userDao.getUserByLoginName(loginName);
	}

}
